import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/ankermatch/ankermatchmodel.dart';
import 'package:toast/toast.dart';

class AnkerMatchSubmitScreen extends StatelessWidget {
  String lpn;
  List<AnkerMatchItem> data;

  @override
  Widget build(BuildContext context) {
    return AnkerMatchSubmitScreenPage(lpn: lpn, data: data);
  }

  AnkerMatchSubmitScreen({
    this.lpn,
    this.data,
  });
}

class AnkerMatchSubmitScreenPage extends StatefulWidget {
  String lpn;
  List<AnkerMatchItem> data;

  AnkerMatchSubmitScreenPage({
    this.lpn,
    this.data,
  });

  @override
  _AnkerMatchSubmitPageState createState() => _AnkerMatchSubmitPageState(lpn: lpn, data: data);
}

class _AnkerMatchSubmitPageState extends BaseState<AnkerMatchSubmitScreen> {
  String lpn;
  List<AnkerMatchItem> data;

  _AnkerMatchSubmitPageState({
    this.lpn,
    this.data,
  });

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "AnkerMatch：Submit";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    next = "Submit";
    getQty();
  }


  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 0, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Row(
            children: [
              Expanded(
                flex: 3, //设置权重
                child: Text(
                  'Batch Number',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                ),
              ),
              Expanded(
                flex: 1, //设置权重
                child: Text(
                  "QTY (0)",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                ),
              ),
            ],
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        AnkerMatchItem tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 3, //设置权重
                  child: Text(
                    Utils.getStringisEmpty(tally.batchNo),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: Text(
                    Utils.getStringisInteger(tally.qty),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  void ankerMatchSubmit(String batchNo) async {
    updateHint('');
    AnkerMatchSubmit ankerMatchSubmit = new AnkerMatchSubmit();
    ankerMatchSubmit.lpn = lpn;
    ankerMatchSubmit.batchNo = batchNo;

    String json = jsonEncode(ankerMatchSubmit);
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.ankerMatchSubmit, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        AnkerMatch ankerMatch = AnkerMatch.fromJson(baseResponse.data);
        textEditingController.text = "";
        data = ankerMatch.batchNoList;
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  int total = 0;
  String listHint = "QTY (0)";

  void getQty() {
    if (data == null) {
      data = new List();
    }
    total = 0;
    for (AnkerMatchItem ankerMatchItem in data) {
      total = total + Utils.getIntegerisEmpty(ankerMatchItem.qty);
    }
    listHint = "QTY (${total})";
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    if (code == "WO202402070002" || code == "PO2345DSDC010001-2-2" || code == "PO2345DSDC010001-2-1" || code == "PO2345DSDC010001-2-2") {
      showDialog(
        context: context,
        builder: (context) => AnkerMatchSubmitConfirmDialog(isGood: false),
      ).then((value) => {
            if (value != null && value) {ankerMatchSubmit(textEditingController.text)}
          });
    } else {
      showDialog(
        context: context,
        builder: (context) => AnkerMatchSubmitConfirmDialog(isGood: true),
      ).then((value) => {
            if (value != null && value) {ankerMatchSubmit(textEditingController.text)}
          });
    }
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}

class AnkerMatchSubmitConfirmDialog extends StatefulWidget {
  bool isGood;

  AnkerMatchSubmitConfirmDialog({this.isGood});

  @override
  _AnkerMatchSubmitConfirmDialogState createState() => _AnkerMatchSubmitConfirmDialogState(isGood: isGood);
}

class _AnkerMatchSubmitConfirmDialogState extends State<AnkerMatchSubmitConfirmDialog> {
  bool isGood;

  _AnkerMatchSubmitConfirmDialogState({this.isGood});

  @override
  Widget build(BuildContext context) {
    return Dialog(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12.0),
      ),
      child: Padding(
        padding: const EdgeInsets.only(top: 15, left: 15, right: 15),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            Text(isGood ? "Good!" : "Damaged!",
                style: TextStyle(
                  fontSize: 16,
                  color: isGood ? MyAppTheme.color_008000 : MyAppTheme.red,
                )),
            Text(isGood ? "need to put away" : "need to take it out!", style: MyAppTheme.text),
            SizedBox(height: 16.0),
            Image.asset(
              isGood ? 'assets/images/ic_arker_good.png' : 'assets/images/ic_arker_damaged.png',
              width: 100,
              height: 100,
            ),
            Row(
              children: <Widget>[
                Expanded(
                    flex: 1,
                    child: FlatButton(
                      child: Text(
                        'Got It',
                        style: MyAppTheme.titlenearlyBlue16,
                      ),
                      onPressed: () {
                        Navigator.of(context).pop(true);
                      },
                    )),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
